import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import './styles/index.scss'
import { permission, role } from './directives/permission'

// 处理 ResizeObserver 错误（开发环境警告）
const resizeObserverError = 'ResizeObserver loop completed with undelivered notifications.'
const originalError = console.error
console.error = (...args) => {
  if (args[0] === resizeObserverError) {
    return // 忽略 ResizeObserver 错误
  }
  originalError.apply(console, args)
}

// 全局错误处理
window.addEventListener('error', (event) => {
  if (event.message.includes(resizeObserverError)) {
    event.preventDefault()
    return false
  }
})

window.addEventListener('unhandledrejection', (event) => {
  if (event.reason?.message?.includes(resizeObserverError)) {
    event.preventDefault()
    return false
  }
})

// 处理 ResizeObserver 错误
const originalResizeObserver = window.ResizeObserver
if (originalResizeObserver) {
  window.ResizeObserver = class ResizeObserver extends originalResizeObserver {
    constructor(callback) {
      super((entries, observer) => {
        try {
          callback(entries, observer)
        } catch (error) {
          if (!error.message.includes(resizeObserverError)) {
            console.error('ResizeObserver error:', error)
          }
        }
      })
    }
  }
}

const app = createApp(App)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 注册权限控制指令
app.directive('permission', permission)
app.directive('role', role)

app.use(store)
   .use(router)
   .use(ElementPlus)
   .mount('#app')
